<template>
  <div class="checkbox-popup">
    <div v-for="item in list" :key="item.id" class="first-item flex">
      <el-checkbox :model-value="checkboxFilter(item.children).length === item.children.length"
        :indeterminate="checkboxFilter(item.children).length > 0 && checkboxFilter(item.children).length < item.children.length"
        :label="item.name" fill="@main-color" text-color="@main-color" @click="checkboxChange(item.children)"
        class="first-checkbox" />
      <p class="line"></p>
      <div class="checkbox-children flex flex-wrap">
        <el-checkbox v-for="child in item.children" :key="child.id" :model-value="checked.some(cate => cate === child.id)"
          :label="child.name" @change="checkboxChildChange(child.id)" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps(['list', 'checked']);
const emit = defineEmits(['change']);

const checkboxChange = (list) => {
  let arr = props.checked;
  if (list.filter(child => arr.some(cate => cate === child.id)).length === list.length) {
    arr = arr.filter(cate => list.every(child => child.id !== cate));
  } else {
    list.some(child => {
      if (arr.every(cate => cate !== child.id)) {
        arr.push(child.id);
      }
    })
  }
  emit('change', arr);
}
const checkboxChildChange = id => {
  let arr = props.checked;
  if (arr.some(cate => cate === id)) {
    arr = arr.filter(cate => cate !== id);
  } else {
    arr.push(id);
  }
  emit('change', arr);
}
const checkboxFilter = (list) => {
  return list.filter(child => props.checked.some(cate => cate === child.id));
}
</script>

<style lang="less" scoped>
.checkbox-popup {
  max-height: 230px;
  padding: 10px 12px 12px;
  overflow-y: auto;

  .first-item {
    padding-top: 12px;

    &:first-child {
      padding-top: 0;
    }

    .first-checkbox {
      width: 100px;
    }

    .line {
      width: 1px;
      background: #ededed;
      margin-right: 20px;
    }

    .checkbox-children {
      width: 679px;
      border-bottom: 1px solid #ededed;
    }
  }
}
</style>
